import { Action } from 'routing-controllers';
import JsonwebToken, { VerifyErrors, JwtPayload } from 'jsonwebtoken'
import config from '@/config'
import { JsonResult, msgList } from '@/utils/jsonResult';

/**
 * Token检验的装饰器代码实现
 */
export class AuthorizationChecker {
    json: JsonResult<null> = new JsonResult
    async check(action: Action, roles: string[]): Promise<boolean> {
        if (action.request.headers.hasOwnProperty("token")) {
            const token = action.request.headers['token'];
            return new Promise<boolean>((success: (value: boolean | PromiseLike<boolean>) => void) => {
                JsonwebToken.verify( token, config.jwtKey, (err: VerifyErrors | null, decoded: JwtPayload | undefined | string) =>{
                    if(err){
                        throw this.json.error(null,msgList.DecodedTokenError)
                    }else{
                        action.request.headers['token'] = decoded
                        success(true)
                    }
                });
            })
        }
        throw this.json.error(null,msgList.NoFoundToken)
    }
}